package eteam.aps.common.component;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import eteam.aps.common.exceptions.BusinessException;
import eteam.aps.common.helper.Helper;
import eteam.aps.common.helper.JwtUtils;
import eteam.aps.systeminterface.model.dto.VerifyTokenDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取当前登录用户
 *
 * 使用 redis
 */
@Component
public class LoginUserRedisService {

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	/**
	 * 查询当前用户信息
	 *
	 * @return 用户数据
	 */
	public VerifyTokenDto getUser() throws Exception {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
				.getRequest();
		String token = request.getHeader("token");
		// 判断token是否为空
		if (Helper.isEmpty(token)) {
			throw  new BusinessException(HttpStatus.UNAUTHORIZED, "Token无效");
		}
		return getUser(token);
	}

	/**
	 * 查询当前用户信息
	 *
	 * @return 用户数据
	 * @throws JsonProcessingException
	 * @throws JsonMappingException
	 */
	public VerifyTokenDto getUser(String token) throws Exception {
		// 解析token，并提取用户信息
		String useId = JwtUtils.verifyTokenRetUserId(token);
		String jsonStr = JwtUtils.verifyTokenRetJson(token);
		redisTemplate.opsForValue().set(useId, jsonStr);
		VerifyTokenDto tokenDto = Helper.JACKSON_OBJECT_MAPPER.readValue(jsonStr.toString(), VerifyTokenDto.class);
		return tokenDto;
	}

}